// 将音频转换为WAV格式
const convert_to_wav = (audio_blob) => {
	return new Promise((resolve) => {
		const audio_context = new (window.AudioContext || window.webkitAudioContext)()
		const file_reader = new FileReader()

		file_reader.onload = async (e) => {
			try {
				const array_buffer = e.target.result
				const audio_buffer = await audio_context.decodeAudioData(array_buffer)

				// 获取音频数据
				const channels = audio_buffer.numberOfChannels
				const sample_rate = audio_buffer.sampleRate
				const length = audio_buffer.length

				// 创建WAV文件头
				const buffer = new ArrayBuffer(44 + length * channels * 2)
				const view = new DataView(buffer)

				// WAV文件头
				const write_string = (offset, string) => {
					for (let i = 0; i < string.length; i++) {
						view.setUint8(offset + i, string.charCodeAt(i))
					}
				}

				write_string(0, 'RIFF')
				view.setUint32(4, 36 + length * channels * 2, true)
				write_string(8, 'WAVE')
				write_string(12, 'fmt ')
				view.setUint32(16, 16, true)
				view.setUint16(20, 1, true)
				view.setUint16(22, channels, true)
				view.setUint32(24, sample_rate, true)
				view.setUint32(28, sample_rate * channels * 2, true)
				view.setUint16(32, channels * 2, true)
				view.setUint16(34, 16, true)
				write_string(36, 'data')
				view.setUint32(40, length * channels * 2, true)

				// 写入音频数据
				let offset = 44
				for (let i = 0; i < length; i++) {
					for (let channel = 0; channel < channels; channel++) {
						const sample = Math.max(-1, Math.min(1, audio_buffer.getChannelData(channel)[i]))
						view.setInt16(offset, sample < 0 ? sample * 0x8000 : sample * 0x7FFF, true)
						offset += 2
					}
				}

				resolve(new Blob([buffer], { type: 'audio/wav' }))
			} catch (error) {
				console.error('音频转换失败:', error)
				// 如果转换失败，返回原始音频
				resolve(audio_blob)
			}
		}

		file_reader.readAsArrayBuffer(audio_blob)
	})
}

export default convert_to_wav